import { login, logout, authLogin, getInfo, refreshUser, refreshToken, refreshUserClient } from '@/api/login'
import { getToken, setToken, setLs, clearLs, setExpiresIn } from '@/utils/auth'

const user = {
  state: {
    token: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    authorities: [],
    attrs: {},
    param: {
      param: [],
      data: []
    },
    phoneNum: '',

  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_AUTHORITIES: (state, authorities) => {
      state.authorities = authorities
    },
    SET_ATTRS(state, attrs) {
      state.attrs = attrs
    },
    SET_PARAM(state, param) {
      state.param[param.key].push(param.data)
    },
    SET_PHONENUM(state, phoneNum) {
      state.phoneNum = phoneNum
    }
  },

  actions: {
    // 登录
    Login({ commit }, data) {
      setToken(data.accessToken)
      commit('SET_TOKEN', data.accessToken)
      setLs('SM2PublicKey', data.secretKey?.publicKey)
      setLs('SM2PrivateKey', data.secretKey?.privateKey)
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        const token = state.token
        commit('SET_AUTHORITIES', [])
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        clearLs()
        resolve()
        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   commit('SET_PERMISSIONS', [])
        //   clearLs()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 以下暂时没用

    // 授权登录
    AUTHLogin({ commit }, data){
      const code = data.code
      return new Promise((resolve, reject) => {
        authLogin(code).then(res => {
          let data = res.data
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        let res = { code: 0, result: {}, message: '操作成功'}
        resolve(res)
        /*getInfo().then(res => {
          const user = res.data
          const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : `${process.env.VUE_APP_OSS_URL}${user.avatar}`;
          const access = []
          if (user.authorities) {
            user.authorities.map(item => {
              if (item.authority) {
                access.push(item.authority)
              }
            })
          }
          // 转换权限
          commit('SET_AUTHORITIES', access)
          const { attrs } = user
          const roles = []
          if (attrs.roles && attrs.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            attrs.roles.map(item => {
              if (item.roleCode) {
                roles.push(item.roleCode)
              }
            })
            commit('SET_ROLES', roles)
            // commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.username)
          commit('SET_AVATAR', avatar)
          commit('SET_ATTRS', user.attrs)
          commit('SET_PHONENUM', user.phoneNum)
          resolve(res)
        }).catch(error => {
          reject(error)
        })*/
      })
    },

    // 刷新用户信息
    RefreshUser({ commit, state }){
      return new Promise((resolve, reject) => {
        refreshUser().then(res => {
          const user = res.data
          const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : `${process.env.VUE_APP_OSS_URL}${user.avatar}`;
          const access = []
          if (user.authorities) {
            user.authorities.map(item => {
              if (item.authority) {
                access.push(item.authority)
              }
            })
          }
          // 转换权限
          commit('SET_AUTHORITIES', access)
          const { attrs } = user
          const roles = []
          if (attrs.roles && attrs.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            attrs.roles.map(item => {
              if (item.roleCode) {
                roles.push(item.roleCode)
              }
            })
            commit('SET_ROLES', roles)
            // commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.username)
          commit('SET_AVATAR', avatar)
          commit('SET_ATTRS', user.attrs)
          commit('SET_PHONENUM', user.phoneNum)

          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    RefreshUserClient({commit, state}){
      return new Promise((resolve, reject) => {
        refreshUserClient().then(res => {
          let data = res.data
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token).then(res => {
          setExpiresIn(res.data)
          commit('SET_EXPIRES_IN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        clearLs()
        resolve()
      })
    },

    // 存储成本预测参数
    SetParam({ commit }, data){
      commit('SET_PARAM', data)
    }
  }
}

export default user
